import java.util.*;

public class MyBinarytree {
    static class TreeNode {
        public char val;
        public TreeNode left;//左孩子的引用
        public TreeNode right;//右孩子的引用

        public TreeNode(char val) {
            this.val = val;
        }
    }

    /**
     * 创建一棵二叉树 返回这棵树的根节点
     *
     * @return
     */
    public TreeNode createTree() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        E.right = H;
        C.left = F;
        C.right = G;
        return A;
    }

    public TreeNode createTree2() {
        TreeNode A = new TreeNode('A');
        TreeNode B = new TreeNode('B');
        TreeNode C = new TreeNode('C');
        TreeNode D = new TreeNode('D');
        TreeNode E = new TreeNode('E');
        TreeNode F = new TreeNode('F');
        TreeNode G = new TreeNode('G');
        TreeNode H = new TreeNode('H');
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = E;
        C.left = F;
        C.right = G;
        return A;
    }

    // 前序遍历
    public void preOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        System.out.print(root.val + " ");
        preOrder(root.left);
        preOrder(root.right);
    }

    // 中序遍历
    public void inOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        inOrder(root.left);
        System.out.print(root.val + " ");
        inOrder(root.right);
    }

    // 后序遍历
    void postOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        postOrder(root.left);
        postOrder(root.right);
        System.out.print(root.val + " ");
    }

    public static int nodeSize = 0;// 记录二叉树的结点个数

    /**
     * 获取树中节点的个数：遍历思路
     */
    public void size(TreeNode root) {
        if (root == null) {
            return;
        }
        nodeSize++;
        size(root.left);
        size(root.right);
    }

    /**
     * 获取节点的个数：子问题的思路
     *
     * @param root
     * @return
     */
    public int size2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        // 难点 -> 画图 在叶子结点时 会返回1 根是最后加上的
        return size2(root.left) + size2(root.right) + 1;
    }


    /**
     * 获取 "叶子" 节点的个数：遍历思路
     */
    public static int leafSize = 0;

    public void getLeafNodeCount1(TreeNode root) {
        if (root == null) {
            return;
        }
        if (root.left == null && root.right == null) {
            leafSize++;
        }
        getLeafNodeCount1(root.left);
        getLeafNodeCount1(root.right);
    }

    /**
     * 获取 "叶子" 节点的个数：子问题
     */
    public int getLeafNodeCount2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        if (root.left == null && root.right == null) {
            return 1;
        }
        return getLeafNodeCount2(root.left) + getLeafNodeCount2(root.right);
    }

    /**
     * 获取第K层节点的个数
     */
    public int getKLevelNodeCount(TreeNode root, int k) {
        if (root == null) {
            return 0;
        }
        if (k <= 0) {
            return 0;
        }
        if (k == 1) {
            return 1;
        }
        k--;
        return getKLevelNodeCount(root.left, k) + getKLevelNodeCount(root.right, k);
    }

    /**
     * 获取二叉树的高度
     * 时间复杂度：O(N)
     */
    public int getHeight(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = getHeight(root.left);
        int rightHeight = getHeight(root.right);
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    /**
     * 检测值为value的元素是否存在
     * 返回值可改:TreeNode -> boolean
     *
     * @param root
     * @param val
     * @return
     */
    public TreeNode find(TreeNode root, char val) {
        if (root == null) {
            return null;
        }
        if (root.val == val) {
            return root;
        }
        TreeNode treeNode1 = find(root.left, val);
        if (treeNode1 != null) {
            return treeNode1;
        }
        TreeNode treeNode2 = find(root.right, val);
        if (treeNode2 != null) {
            return treeNode2;
        }
        return null;
    }

    /**
     * 层序遍历 (非递归)
     * 变形: 树的左/右视图
     *
     * @param root
     */
    public void levelOrder(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            System.out.print(cur.val + " ");
            if (cur.left != null) {
                queue.offer(cur.left);
            }
            if (cur.right != null) {
                queue.offer(cur.right);
            }

        }
    }


    /**
     * 判断一棵树是不是完全二叉树
     *
     * @param root
     * @return
     */
    public boolean isCompleteTree(TreeNode root) {
        if (root == null) {
            return true;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode cur = queue.poll();
            if (cur != null) {
                queue.offer(cur.left);
                queue.offer(cur.right);
            } else {
                break;
            }
        }
        while (!queue.isEmpty()) {
            TreeNode ret = queue.poll();
            if (ret != null) {
                return false;
            }
        }
        return true;
    }

    // ---------------二叉树相关oj题------------------------

    /**
     * 判断两颗树是否相同
     * 时间复杂度O(min(n,m))
     * 最差情况 相等是 n==m
     *
     * @param p
     * @param q
     * @return
     */
    public boolean isSameTree(TreeNode p, TreeNode q) {
        if (p != null && q == null || p == null && q != null) {
            return false;
        }
        if (p == null && q == null) {
            return true;
        }
        if (p.val != q.val) {
            return false;
        }
        // 代码简单思路难 递归 判断左子树和右子树
        return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }

    /**
     * 有问题待解决
     * 另一颗树的子树
     * 时间复杂度 O(n*m)
     *
     * @param root
     * @param subRoot
     * @return
     */
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null || subRoot == null) {
            return false;
        }
        if (isSameTree(root, subRoot)) {
            return true;
        }
        if (isSameTree(root.left, subRoot)) {
            return true;
        }
        if (isSameTree(root.right, subRoot)) {
            return true;
        }
        return false;
    }

    // 二叉树最大深度
    public int maxDepth(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        return leftHeight > rightHeight ? leftHeight + 1 : rightHeight + 1;
    }

    /**
     * 判断一颗二叉树是否是平衡二叉树 (字节 考过的面试题)
     * 每个结点的左右子树结点的绝对值 <= 1
     * 时间复杂度: O(n^2) 可以进行优化 优化之后为 O(n)
     *
     * @param root
     * @return
     */
    public boolean isBalanced(TreeNode root) {
        if (root == null) {
            return true;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        return Math.abs(leftHeight - rightHeight) <= 1
                && isBalanced(root.left)
                && isBalanced(root.right);
    }

    /**
     * 优化后的版本
     *
     * @param root
     * @return
     */
    public boolean isBalanced2(TreeNode root) {
        if (root == null) {
            return true;
        }
        return maxDepth2(root) >= 0;
    }

    public int maxDepth2(TreeNode root) {
        if (root == null) {
            return 0;
        }
        int leftHeight = maxDepth(root.left);
        int rightHeight = maxDepth(root.right);
        if (Math.abs(leftHeight - rightHeight) <= 1) {
            return Math.max(leftHeight, rightHeight) + 1;
        } else {
            return -1;
        }
    }

    /**
     * 是否是对称二叉树
     * 轴对称 左树与右树是否对称
     *
     * @param root
     * @return
     */
    public boolean isSymmetric(TreeNode root) {
        if (root == null) {
            return true;
        }
        return isSymmetricChild(root.left, root.right);
    }

    public boolean isSymmetricChild(TreeNode leftTree, TreeNode rightTree) {
        if (leftTree == null && rightTree != null || leftTree != null && rightTree == null) {
            return false;
        }
        if (leftTree == null && rightTree == null) {
            return true;
        }
        if (leftTree.val != rightTree.val) {
            return false;
        }

        return isSymmetricChild(leftTree.left, rightTree.right) &&
                isSymmetricChild(leftTree.right, rightTree.left);
    }

    /**
     * 层序遍历
     * 将每一层的结点 放在一个List中
     *
     * @param root
     * @return 二维数组
     */
    public List<List<Character>> levelOrder2(TreeNode root) {
        List<List<Character>> lists = new ArrayList<>();
        if (root == null) {
            return lists;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Character> list = new ArrayList<>();

            while (size > 0) {
                TreeNode cur = queue.poll();
                size--;
                list.add(cur.val);
                if (cur.left != null) {
                    queue.offer(cur.left);
                }
                if (cur.right != null) {
                    queue.offer(cur.right);
                }
            }
            lists.add(list);
        }
        return lists;
    }

    /**
     * 前序遍历构造二叉树
     *
     * @return
     */
    public int i = 0;

    public TreeNode createTree3(String s) {
        TreeNode root = null;
        if (s.charAt(i) != '#') {
            root = new TreeNode(s.charAt(i));
            i++;
            root.left = createTree3(s);
            root.right = createTree3(s);
        } else {
            i++;
        }
        return root;
    }

    /**
     * 二叉树的最近公共祖先
     * 方法1: 假设是一棵二叉搜索树
     * 方法2: 使用栈,求交点
     *
     * @param root
     * @param p
     * @param q
     * @return
     */
    public TreeNode lowestCommonAncestor1(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null) {
            return null;
        }
        if (q == root || p == root) {
            return root;
        }
        TreeNode leftNode = lowestCommonAncestor1(root.left, p, q);
        TreeNode rightNode = lowestCommonAncestor1(root.right, p, q);
        if (leftNode == null && rightNode == null) {
            return root;
        } else if (leftNode != null) {
            return leftNode;
        } else {
            return rightNode;
        }
    }

    public TreeNode lowestCommonAncestor2(TreeNode root, TreeNode p, TreeNode q) {
        if (root == null || p == null || q == null) {
            return null;
        }
        Stack<TreeNode> stackP = new Stack<>();
        Stack<TreeNode> stackQ = new Stack<>();
        getPath(root, p, stackP);
        getPath(root, q, stackQ);

        while (stackP.size() != stackQ.size()) {
            if (stackP.size() > stackQ.size()) {
                stackP.pop();
            } else {
                stackQ.pop();
            }
        }
        // p和q一定在二叉树中
        while (true) {
            if (stackP.peek() == stackQ.peek()) {
                return stackP.pop();
            }
            stackP.pop();
            stackQ.pop();
        }
        // 下面是 p和q不一定在二叉树中的情况
        /*while (!stackP.empty() && !stackQ.empty()){
            if (stackP.peek() == stackQ.peek()){
                return stackP.pop();
            }
            stackP.pop();
            stackQ.pop();
        }
        return null;*/
    }

    /**
     * 找到root到node之间的结点,存到stack中
     *
     * @param root
     * @param node
     * @param stack
     * @return
     */
    public boolean getPath(TreeNode root, TreeNode node, Stack<TreeNode> stack) {
        if (root == null || node == null) {
            return false;
        }
        stack.push(root);
        if (root == node) {
            return true;
        }
        boolean ret1 = getPath(root.left, node, stack);
        if (ret1) {
            return true;
        }
        boolean ret2 = getPath(root.right, node, stack);
        if (ret2) {
            return true;
        }
        stack.pop();
        return false;
    }

    /**
     * 二叉搜索树与双向链表
     * 中序遍历就可以了
     * 要求:
     * 空间复杂度O(1)
     * 时间复杂度O(n)
     *
     * @param pRootOfTree
     * @return
     */
    public TreeNode Convert(TreeNode pRootOfTree) {
        if (pRootOfTree == null) {
            return null;
        }
        ConvertChild(pRootOfTree);
        TreeNode head = pRootOfTree;
        while (head.left != null) {
            head = head.left;
        }
        return head;
    }

    public TreeNode prev = null;

    public void ConvertChild(TreeNode root) {
        if (root == null) {
            return;
        }
        ConvertChild(root.left);
        root.left = prev;
        if (prev != null) {
            prev.right = root;
        }
        prev = root;
        ConvertChild(root.right);
    }

    /**
     * 用前序和中序遍历结果构造二叉树
     *
     * @param preorder
     * @param inorder
     * @return
     */
    public int preIndex = 0;

    public TreeNode buildTree(char[] preorder, char[] inorder) {
        return buildTreeChild(preorder, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild(char[] preorder, char[] inorder, int inbegin, int inend) {
        if (inbegin > inend) {
            return null;
        }

        TreeNode root = new TreeNode(preorder[preIndex]);

        int rootIndex = findInorderIndex(inorder, preorder[preIndex], inbegin, inend);
        preIndex++;

        root.left = buildTreeChild(preorder, inorder, inbegin, rootIndex - 1);
        root.right = buildTreeChild(preorder, inorder, rootIndex + 1, inend);

        return root;
    }

    public int findInorderIndex(char[] inorder, char val, int inbegin, int inend) {
        for (int j = inbegin; j <= inend; j++) {
            if (inorder[j] == val) {
                return j;
            }
        }
        return -1;
    }

    /**
     * 用中序和后序遍历结果构造二叉树
     *
     * @param inorder
     * @param postorder
     * @return
     */
    public int postIndex = 0;

    public TreeNode buildTree2(char[] inorder, char[] postorder) {
        postIndex = postorder.length - 1;
        return buildTreeChild(postorder, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTreeChild2(char[] postorder, char[] inorder, int inbegin, int inend) {
        if (inbegin > inend) {
            return null;
        }

        TreeNode root = new TreeNode(postorder[postIndex]);
        int rootIndex = findInorderIndex(inorder, postorder[postIndex], inbegin, inend);
        postIndex--;

        root.right = buildTreeChild2(postorder, inorder, rootIndex + 1, inend);
        root.left = buildTreeChild2(postorder, inorder, inbegin, rootIndex - 1);

        return root;
    }

    public int findInorderIndex2(char[] inorder, char val, int inbegin, int inend) {
        for (int j = inbegin; j <= inend; j++) {
            if (inorder[j] == val) {
                return j;
            }
        }
        return -1;
    }

    /**
     * 根据二叉树创建字符串
     * 输入：root = [1,2,3,4]
     * 输出："1(2(4))(3)"
     *
     * @param root
     * @return
     */
    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        tree2str(root, stringBuilder);
        return stringBuilder.toString();
    }

    public void tree2str(TreeNode root, StringBuilder stringBuilder) {
        if (root == null) {
            return;
        }
        stringBuilder.append(root.val);

        if (root.left != null) {
            stringBuilder.append("(");
            tree2str(root.left, stringBuilder);
            stringBuilder.append(")");
        } else {
            if (root.right == null) {
                return;
            } else {
                // 左边为null,右边不为空 -> ()代表左数为null
                stringBuilder.append("()");
            }
        }

        if (root.right == null) {
            return;
        } else {
            stringBuilder.append("(");
            tree2str(root.right, stringBuilder);
            stringBuilder.append(")");
        }
    }

    /**
     * 二叉树非递归实现前序遍历
     *
     * @param root
     * @return
     */
    public List<Character> preorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                // 如果返回值为void 这个地方就可以把结果打印出来
                ret.add(cur.val);
                cur = cur.left;
            }
            cur = stack.pop();
            cur = cur.right;
        }
        return ret;
    }

    /**
     * 二叉树非递归实现中序遍历
     *
     * @param root
     * @return
     */
    public List<Character> inorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        if (root == null) {
            return ret;
        }
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
            cur = stack.pop();
            ret.add(cur.val);
            cur = cur.right;
        }
        return ret;
    }

    /**
     * 二叉树非递归实现后序遍历
     *
     * @param root
     * @return
     */
    public List<Character> postorderTraversal(TreeNode root) {
        List<Character> ret = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        TreeNode prev = null;

        while (cur != null || !stack.empty()) {
            while (cur != null) {
                stack.push(cur);
                cur = cur.left;
            }
        }

        TreeNode top = stack.peek();
        if (top.right != null || prev != top.right) {
            stack.pop();
            ret.add(top.val);
            prev = top;
        } else {
            cur = top.right;
        }
        return ret;
    }
}
